package com.liuwei.spring.cloud.framework.feigns.provider;
/**
 * Description :
 *
 * @Author Evan Liu
 * @Date 2019年4月24日
 */
/*
 * Copyright 2012-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.liuwei.spring.cloud.common.utils.StringPool;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;

/**
 * 拦截所有的 /api/feign/* 请求进行鉴权
 * @author liuwei
 */
@Slf4j
public class FeignAuthFilter extends OncePerRequestFilter implements Ordered {
    /** Not LOWEST_PRECEDENCE, but near the end, so it has a good chance of catching all enriched headers, but users can add stuff after this if they want to */
    private int order = Ordered.LOWEST_PRECEDENCE - 10;

    @Override
    public int getOrder() {
        return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    /**
     * request 的inputStream和response 的outputStream默认情况下是只能读一次， 不可重复读
     * https://www.jianshu.com/p/afdd31bfbf94
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // 获取 TraceId
        String traceId = "";
        String url = request.getRequestURI().toString();

        //请求及相应封装
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

        // feign 权限校验
        boolean authed = false;
        String token = StringPool.EMPTY;
        try {
        } catch (Exception e) {
            throw e;
        }
        filterChain.doFilter(requestWrapper, responseWrapper);
    }
}


